import { Component, OnInit } from '@angular/core';
import { HttpResponse } from '@angular/common/http';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { FormBuilder, Validators } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs';

import { IItemType, ItemType } from 'app/shared/model/item-type.model';
import { ItemTypeService } from './item-type.service';

@Component({
  selector: 'jhi-item-type-update',
  templateUrl: './item-type-update.component.html',
})
export class ItemTypeUpdateComponent implements OnInit {
  isSaving = false;

  editForm = this.fb.group({
    id: [],
    typeName: [],
    offset: [],
    des: [],
    memo: [],
  });

  constructor(protected itemTypeService: ItemTypeService, protected activatedRoute: ActivatedRoute, private fb: FormBuilder) {}

  ngOnInit(): void {
    this.activatedRoute.data.subscribe(({ itemType }) => {
      this.updateForm(itemType);
    });
  }

  updateForm(itemType: IItemType): void {
    this.editForm.patchValue({
      id: itemType.id,
      typeName: itemType.typeName,
      offset: itemType.offset,
      des: itemType.des,
      memo: itemType.memo,
    });
  }

  previousState(): void {
    window.history.back();
  }

  save(): void {
    this.isSaving = true;
    const itemType = this.createFromForm();
    if (itemType.id !== undefined) {
      this.subscribeToSaveResponse(this.itemTypeService.update(itemType));
    } else {
      this.subscribeToSaveResponse(this.itemTypeService.create(itemType));
    }
  }

  private createFromForm(): IItemType {
    return {
      ...new ItemType(),
      id: this.editForm.get(['id'])!.value,
      typeName: this.editForm.get(['typeName'])!.value,
      offset: this.editForm.get(['offset'])!.value,
      des: this.editForm.get(['des'])!.value,
      memo: this.editForm.get(['memo'])!.value,
    };
  }

  protected subscribeToSaveResponse(result: Observable<HttpResponse<IItemType>>): void {
    result.subscribe(
      () => this.onSaveSuccess(),
      () => this.onSaveError()
    );
  }

  protected onSaveSuccess(): void {
    this.isSaving = false;
    this.previousState();
  }

  protected onSaveError(): void {
    this.isSaving = false;
  }
}
